<?php
/**
 * PHP Framework Core Naming Convention Mapper class
 *
 * @author Andrew <andrew@vitche.com>
 * @author Frozen Rain <frozenrain@mail.ru>
 **/

class NamingConventionMapper {

    /**
     * Phrase mappings which can be used while building names
     * @var Array
     **/
    private static $_mappings = array();

    public static function addMapping($key, $value) {
        NamingConventionMapper::$_mappings[$key] = $value;
    }

    // Converts a name given in the camelize notation to the Oracle notation
    public static function camelizeToOracle($value) {

        return NamingConventionMapper::windowsAPIToOracle($value);
    }

    // Converts a name given in the Windows API notation to the Oracle notation
    public static function windowsAPIToOracle($str) {

        $strRes = '';

        // Insert '_' before big letters in the middle of the word
        for ($i = 0; $i < strlen($str); $i++) {
            $letter = $str[$i];
            if ('A' <= $letter && $letter <= 'Z' && 0 != $i) {
                $strRes .= '_' . $letter;
            } else {
                $strRes .= $letter;
            }
        }

        return strtolower($strRes);
    }

    // Converts a name to the plural form
    public static function toPlural($value) {

        // Change 'y' in the end of the word to 'ie'
        $strLastLetter = substr($value, strlen($value) - 1, 1);
        if ('y' == $strLastLetter) {
            $value = substr($value, 0, strlen($value) - 1) . 'ie';
        }

        // Add the 's' letter to get the multiple form
        $value .= 's';

        return $value;
    }

    // Converts a namespace name to a folder path relative to the current
    // root folder
    // TODO: Improve performance by algorithmic optimization
    // TODO: Improve performance by using local cache
    public static function namespaceToFolder($value) {

        global $root;

        $result = '';
        $arParts = explode('.', $value);
        $length = count($arParts) - 1;
        for ($i = $length; $i >= 0; $i--) {
            $temp = $root . '/';
            for ($k = 0; $k <= $i; $k++) {
                $temp .= $arParts[$k];
                if ($k != $i) {
                    $temp .= '.';
                }
            }
            for ($k = $i + 1; $k <= $length; $k++) {
                $temp .= '/' .$arParts[$k];
            }
            if (is_dir($temp)) {
                $result = $temp;
            }
        }

        // Generate a path which can be used for storing emitted code
        if (empty($result)) {

            $result = $root . '/' . implode('/', $arParts);
        }

        return $result;
    }

    /**
     * Maps the given phrase according to the available mapping rules
     **/
    public static function mapPhrase($phrase) {
        return str_replace(array_keys(NamingConventionMapper::$_mappings), array_values(NamingConventionMapper::$_mappings), $phrase);
    }
}
?>